<?php
/**
 * @Author:      ZH
 * @DateTime:    2016-2-16 15:32:48
 * @Description: 用于 pms 订货单
 */
class PMSPlanOrderController extends BaseController {
    /**
     *  采购项列表
     * */
    public function planProductsList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $page_size = Input::get("page_size",25);
            $page = Input::get("page",1);
            
            if(Input::get("key") != ""){  
                $product_ids = [0];
                $products = SupplyItem::where("retrieval_code","like","%".Input::get("key")."%") -> get();
                if(!empty($products)){
                    foreach ($products as $v) {
                        $product_ids[] = $v->id;
                    }
                }
            }

            $plan_products = PMSPlanProducts::where("is_split",0);
            if(Input::get("pms_code") != "") $plan_products->where("pms_code","like","%".Input::get("pms_code")."%");//采购单号
            if(Input::get("key") != "" && !empty($product_ids)) $plan_products->whereIn("product_id",$product_ids); //商品关键字
            if(Input::get("status") != "") $plan_products->where("pms_plan_products.status",Input::get("status")); //根据状态搜索
            if(Input::get("from_key") != "") $plan_products->where("from_key","like","%".Input::get("from_key")."%"); //根据来源搜索

            $count = $plan_products->count();
            $plan_products = $plan_products->skip($page_size*($page-1))->take($page_size)->orderBy("created_at","DESC")->get();
            if(!empty($plan_products)) {
               foreach($plan_products as $v){
                   $v->product_info =  SupplyItem::with(['unit'])->find($v->product_id);
               }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["count"=>$count,"lists"=>$plan_products,'status'=>PMSPlanProducts::$status]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/planProductsList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     *  采买记录
     * */
    public function ProductHistory(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $product_id = Input::get("product_id");
            
            $plan_products = PMSPlanProducts::with(["supplier_by"])->select("ppo.*","pms_plan_products.id","pms_plan_products.tax_purchase_price","no_tax_purchase_price")
                        ->leftJoin("pms_plan_order as ppo","ppo.plan_code","=","pms_plan_products.plan_code")
                        ->where("product_id",$product_id)
                        ->where("pms_plan_products.status",3);
            if (Input::get("begin_time") != "") $plan_products->where("ppo.created_at",">", Input::get("begin_time"));
            if (Input::get("end_time") != "") $plan_products->where("ppo.created_at","<", Input::get("end_time"));

            $plan_products = $plan_products->orderBy("ppo.created_at","DESC")
                        ->orderBy("pms_plan_products.id","DESC")
                        ->skip(0)->take(10)
                        ->get();
            if(!empty($plan_products)){
                foreach($plan_products as $v){
                    $v->tax_purchase_price = number_format($v->tax_purchase_price/100,2);
                    $v->no_tax_purchase_price = number_format($v->no_tax_purchase_price/100,2);
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["lists"=>$plan_products]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/ProductHistory", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  拆分采购项 
     * */
    public function cutProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_product_id' => 'required',
                'products' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $plan_product_id = Input::get("plan_product_id");
            $plan_products_info = PMSPlanProducts::find($plan_product_id);
            if(empty($plan_products_info)){
                $response = Lang::get("pms_error.pms_plan_order_product_error_40012");
                break;
            }
            
            if($plan_products_info->status != 1 || $plan_products_info->is_split == 1){
                $response = Lang::get("pms_error.pms_plan_order_products_error_40015");
                break;
            }
            
            $products = json_decode(Input::get('products'));

            try{
                DB::beginTransaction();
                $num = 0;
                foreach ($products as $v){
                    $plan_products = new PMSPlanProducts();
                    $plan_products->pms_code = $plan_products_info->pms_code;
                    $plan_products->product_id = $plan_products_info->product_id;
                    $plan_products->all_num = $v->num;
                    $plan_products->from_key = $plan_products_info->name;
                    $plan_products->pid = $plan_products_info->id;
                    $plan_products->order_products_id = $plan_products_info->order_products_id;
                    $plan_products->from_key = $plan_products_info->from_key;
                    $plan_products->tax_purchase_price = $plan_products_info->tax_purchase_price;
                    $plan_products->no_tax_purchase_price = $plan_products_info->no_tax_purchase_price;
                    $num += $v->num;
                    if (!$plan_products->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_plan_order_products_error_40009"); 
                    }
                }

                if($plan_products_info->all_num != $num){
                    DB::rollback();
                    throw new Exception("pms_error.pms_plan_order_products_error_40014"); 
                }
                
                 $plan_products_info -> is_split = 1;
                 if (!$plan_products_info->save())throw new Exception("pms_error.pms_plan_order_products_error_40013");  
                 
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }

        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/cutProduct", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  生成订货单
     * */
    public function createPlanOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'supplier_id' => 'required',
                'pay_type' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $plan_product_ids = json_decode(Input::get('plan_product_ids'));
            try{
                DB::beginTransaction();
                
                $all_num = 0;//订货数量
                $plan_code = Common::createOrderId();
                
                if(!empty($plan_product_ids)){
                foreach ($plan_product_ids as $v ) {
                    $plan_produc_info = PMSPlanProducts::find($v->id);
                    
                    if(empty($plan_produc_info)) throw new Exception("pms_error.pms_plan_order_product_error_40012"); 
                    if($plan_produc_info->status !=1) throw new Exception("pms_error.pms_plan_order_products_error_40015");
                    $all_num += $plan_produc_info->all_num;
                    $plan_produc_info->plan_code = $plan_code;
                    $plan_produc_info->status = 2;
                    $plan_produc_info->tax_purchase_price = $v->tax_purchase_price * 100;
                    $plan_produc_info->no_tax_purchase_price = $v->no_tax_purchase_price * 100;
                    if(!$plan_produc_info->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_plan_order_product_error_40016");
                    }

                }}
                
                $plan_order = new PMSPlanOrder();
                $plan_order->plan_code = $plan_code;
                $plan_order->supplier_id = Input::get("supplier_id");
                $plan_order->pay_type = Input::get("pay_type");
                $plan_order->address = Input::get("address");
                $plan_order->all_num = $all_num;
                $plan_order->status = 1;
                $plan_order->type = 1;
                $plan_order->created_type = 2;
                $plan_order->created_by =  $res['user']->id;
                if(!$plan_order->save()) {
                    DB::rollback();
                    throw new Exception("pms_error.pms_plan_order_error_40017");
                }
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }
            
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/createPlanOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  供应商查询
     * */
    public function supplierList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $supplier = MaintenanceSupplier::select("id","name")->where("purchase_status",1)->get();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>$supplier,'regular_pay'=>MaintenanceSupplier::$regular_pay]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/supplierList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     *  供应商下的有效订单
     * */
    public function supplierPlanList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'supplier_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $plan_list = PMSPlanOrder::select("plan_code","pay_type","address","status")->where("supplier_id",Input::get("supplier_id"))->where('status',1)->orderBy("created_at","DESC")->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>$plan_list,'regular_pay'=>MaintenanceSupplier::$regular_pay]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/supplierPlanList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  地址查询
     * */
    public function addrssSelect(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'pms_code' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $pms_code = Input::get("pms_code");
            $str = $this->addrssFun($pms_code);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["str"=>$str]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/addrssSelect", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    public function addrssFun($pms_code){
        $pms_code = array_unique(explode(",",$pms_code ));
        $pms_list = PMSOrder::select("pms_code","shop_id")->whereIn("pms_code",$pms_code)->get();
        $shopid_arr = [];
        foreach($pms_list as $v) {
            $shopid_arr[] = $v->shop_id;
        }

        $shop_info = MaintenanceShops::select("id","address")->whereIn("id",$shopid_arr)->get();
        $str = "";
        foreach($shop_info as $v) {
            $str .= $v->address.';';
        }
        return $str;
    }
    
    /**
     *  加入订货单
     * */
    public function addPlanProducts(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_product_ids' => 'required',
                'plan_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $plan_code = Input::get('plan_code');
            $plan_order_info = PMSPlanOrder::find($plan_code);
            if($plan_order_info->status !=1) {
                $response = Lang::get("pms_error.pms_plan_order_status_error_40018");
                break;
            }
            
            $plan_product_ids = json_decode((Input::get('plan_product_ids')));
            
            try{
                DB::beginTransaction();
                $all_num = 0;
                
                foreach ($plan_product_ids as $v ) {
                    $plan_produc_info = PMSPlanProducts::find($v->id);
                    
                    if(empty($plan_produc_info)) throw new Exception("pms_error.pms_plan_order_product_error_40012"); 
                    if($plan_produc_info->status !=1) throw new Exception("pms_error.pms_plan_order_products_error_40015");
                    $all_num += $plan_produc_info->all_num;
                    $plan_produc_info->plan_code = $plan_code;
                    $plan_produc_info->status = 2;
                    $plan_produc_info->tax_purchase_price = $v->tax_purchase_price * 100;
                    $plan_produc_info->no_tax_purchase_price = $v->no_tax_purchase_price * 100;
                    if(!$plan_produc_info->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_plan_order_product_error_40016");
                    }

                }
                
                $plan_order_info->pay_type = Input::get("pay_type");
                $plan_order_info->address .= Input::get("address"); // 加入订货单追加地址
                $plan_order_info->all_num += $all_num;
                $plan_order_info->updated_type = 2;
                $plan_order_info->updated_by =  $res['user']->id;
                if(!$plan_order_info->save()) {
                    DB::rollback();
                    throw new Exception("pms_error.pms_plan_order_error_40017");
                }
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }
            
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/addPlanProducts", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     *  订货单列表
     * */
    public function planOrderList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $page_size = Input::get("page_size",25);
            $page = Input::get("page",1);
            
            $list = PMSPlanOrder::select("pms_plan_order.*","m.name as supplier_name","m.contacts","m.contacts_number")->leftJoin("maintenance_supplier as m","m.id","=","pms_plan_order.supplier_id");
            if(Input::get("address") != "") $list->where("pms_plan_order.address","like","%".Input::get("address")."%");//收货地址模糊搜索
            $code = Input::get("code");
            if( $code != ""){
                $list->where(function($query) use ($code){
                                $query->orWhere("plan_code","like", "%".$code."%")->orWhere("other_order_code","like", "%".$code."%");
                            });//订货单号模糊搜索
            } 
            if(Input::get("status")) $list->where("pms_plan_order.status",Input::get("status"));
            $supplier_str = Input::get("supplier_str");
            if($supplier_str != "") {
                $list->where(function($query) use ($supplier_str){
                                $query->orWhere("m.id","like", "%".$supplier_str."%")->orWhere("m.name","like", "%".$supplier_str."%");
                            });//供应商信息模糊搜索
            }
            
            $count = $list->count(); 
            $list = $list->orderBy("created_at","desc")->skip($page_size*($page-1))->take($page_size)->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["count"=>$count,"list"=>$list,"status"=>PMSPlanOrder::$status]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/planOrderList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  订购单详情
     * */
    public function planOrderInfo(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $plan_code = Input::get("plan_code");
            $info = PMSPlanOrder::select("pms_plan_order.*","m.name as supplier_name","m.contacts","m.contacts_number")
                    ->leftJoin("maintenance_supplier as m","m.id","=","pms_plan_order.supplier_id")
                    ->where("plan_code",$plan_code)->first();
                        
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["info"=>$info,"status"=>PMSPlanOrder::$status,'regular_pay'=>MaintenanceSupplier::$regular_pay]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/planOrderInfo", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     *  编辑第三方单号
     * */
    public function editOtherOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',
                'other_order_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $plan_code = Input::get("plan_code");
            $plan_info = PMSPlanOrder::find($plan_code);
            if ($plan_info->status == 1) {
                $response = Lang::get("pms_error.pms_plan_order_products_error_40015");
                break;
            }

            $plan_info->other_order_code = Input::get("other_order_code");
            $plan_info->updated_by = $res['user']->id;
            if (!$plan_info->save()) {
                $response = Lang::get("pms_error.pms_plan_order_error_40017");
                break;
            }
                        
            $response = array('code' => 0, 'msg' => 'ok', 'result' => []);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/editOtherOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  编辑配送地址
     * */
    public function editAddress(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',
                'address' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $plan_code = Input::get("plan_code");
            $plan_info = PMSPlanOrder::find($plan_code);
            if ($plan_info->status != 1) {
                $response = Lang::get("pms_error.pms_plan_order_products_error_40015");
                break;
            }

            $plan_info->address = Input::get("address");
            $plan_info->updated_by = $res['user']->id;
            if (!$plan_info->save()) {
                $response = Lang::get("pms_error.pms_plan_order_error_40017");
                break;
            }
                        
            $response = array('code' => 0, 'msg' => 'ok', 'result' => []);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/editAddress", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
 /***
  *  取消订货单
  */
    public function delPlanOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $plan_code = Input::get("plan_code");
            $plan_info = PMSPlanOrder::find($plan_code);
            if(empty($plan_info)) {
                $response = Lang::get("pms_error.pms_plan_order_error_40022");
                break;
            }
            if ($plan_info-> status !=1 ) {
                $response = Lang::get("pms_error.pms_plan_order_status_error_40018");
                break;
            }
            
            $plan_product_ids = PMSPlanProducts::where("plan_code",$plan_code)->where("is_split",0)->get();
            $count = PMSPlanProducts::where("plan_code",$plan_code)->where("is_split",0)->count();
            try{
                DB::beginTransaction();
                
                if($count > 0){
                foreach ($plan_product_ids as $v ) {
                    $plan_produc_info = PMSPlanProducts::find($v->id);
                    $plan_produc_info->plan_code = "";
                    $plan_produc_info->status = 1;
                    $plan_produc_info->tax_purchase_price = 0;
                    $plan_produc_info->no_tax_purchase_price = 0;
                    if(!$plan_produc_info->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_plan_order_product_error_40016");
                    }
                    
                }}

                if(!$plan_info->delete()) {
                    DB::rollback();
                    throw new Exception("pms_error.pms_plan_order_error_40019");
                }
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }
            
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/delPlanOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    } 
  /***
 * 提交订货单
    **/
    public function subPlanOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $plan_code = Input::get("plan_code");
            $plan_info = PMSPlanOrder::find($plan_code);
            if(empty($plan_info)) {
                $response = Lang::get("pms_error.pms_plan_order_error_40022");
                break;
            }
            if ($plan_info-> status !=1 ) {
                $response = Lang::get("pms_error.pms_plan_order_status_error_40018");
                break;
            }
            if (empty($plan_info-> address)) {
                $response = Lang::get("pms_error.pms_plan_order_error_40024");
                break;
            }

            
            $plan_product_ids = PMSPlanProducts::where("plan_code",$plan_code)->where("is_split",0)->get();
            $count = PMSPlanProducts::where("plan_code",$plan_code)->where("is_split",0)->count();
            if ($count == 0) {
                $response = Lang::get("pms_error.pms_plan_order_error_40023");
                break;
            }
                        
            try{
                DB::beginTransaction();
                $receive_arr = [];
                
                foreach ($plan_product_ids as $v ) {
                    //订货单商品
                    $plan_produc_info = PMSPlanProducts::find($v->id);
                    $plan_produc_info->status = 3;
                    $plan_produc_info->last_num = $v->all_num;
                    if(!$plan_produc_info->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_plan_order_product_error_40016");
                    }

                    //采购单
                    $pms_order = PMSOrder::find($plan_produc_info->pms_code);
                    $pms_order->ready_num += $v->all_num;
                    $pms_order->last_num -= $v->all_num;
                    $pms_order->status = 5;
                    if(!$pms_order->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_order_error_40008");
                    }
                                                            
                    //采购单商品
                    $pms_product = PMSOrderProducts::find($v->order_products_id);
                    $pms_product->ready_num += $v->all_num;
                    $pms_product->last_num -= $v->all_num;
                    if(!$pms_product->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_order_product_error_40005");
                    }

                    //生成收货单数组
                    if(!array_key_exists($pms_order->shop_id, $receive_arr)){
                        $receive_code = Common::createOrderId();
                        $receive_arr[$pms_order->shop_id]['receive_code'] = $receive_code;
                        $receive_arr[$pms_order->shop_id]['all_num'] = $v->all_num;
                    } else {
                        $receive_code = $receive_arr[$pms_order->shop_id]['receive_code'];
                        $receive_arr[$pms_order->shop_id]['all_num'] += $v->all_num;
                    }

                    //收货单商品
                    $receive_products = new PMSReceiveProducts();
                    $receive_products->receive_code = $receive_code;
                    $receive_products->pms_code = $pms_order->pms_code;
                    $receive_products->plan_products_id = $v->id;
                    $receive_products->plan_code = $plan_code;
                    $receive_products->product_id = $v->product_id;
                    $receive_products->status = 2;
                    $receive_products->all_num = $v->all_num;
                    $receive_products->last_num = $v->all_num;
                    $receive_products->tax_purchase_price = $v->tax_purchase_price;
                    $receive_products->no_tax_purchase_price = $v->no_tax_purchase_price;
                    $receive_products->from_key = $v->from_key;
                    if(!$receive_products->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_receive_products_error_40020");
                    }
                }
                
                //订货单
                $plan_info -> status = 2;
                $plan_info -> submit_at = date("Y-m-d H:i:s");
                if(!$plan_info->save()) {
                    DB::rollback();
                    throw new Exception("pms_error.pms_plan_order_error_40019");
                }
                                
                //收货单   $receive_arr = ["shop_id"=>["receive_code"=>0,"all_num"]]
                foreach($receive_arr as $shop_id => $v){
                    $receive_code = $v["receive_code"];
                    $receive_order = new PMSReceiveOrder();
                    $receive_order->receive_code = $receive_code;
                    $receive_order->plan_code =  $plan_code;
                    $receive_order->shop_id = $shop_id;
                    $receive_order->supplier_id = $plan_info->supplier_id;
                    $receive_order->pay_type = $plan_info->pay_type;
                    $receive_order->address = $plan_info->address;
                    $receive_order->other_order_code = $plan_info->other_order_code;
                    $receive_order->all_num = $v["all_num"];
                    $receive_order->status = 2;
                    $receive_order->created_type = 2;
                    $receive_order->created_by = $res['user']->id;
                    $receive_order->updated_type = 2;
                    $receive_order->updated_by = $res['user']->id;
                    if(!$receive_order->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_receive_order_error_40021");
                    }
                }
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }
            
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/subPlanOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    } 

    /**
     *  品牌信息
     * */
    public function supplyBrand(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $supply_brand = DataSupplyBrand::where("status",1)->get();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>$supply_brand]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/supplyBrand", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     *  订货单下的采购项列表
     * */
    public function planProducts(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $page_size = Input::get("page_size",500);
            $page = Input::get("page",1);
 
            $con_sql = " select count(*)  as count ";
            $select = "select ppp.*, name, code, brand_id, brand_name, model, series_id, series_name";
            $sql = " from pms_plan_products as ppp left join supply_item as sup on ppp.product_id = sup.id where ppp.is_split=0 ";
            if (Input::get("key") != "") $sql .= " AND retrieval_code like '%".Input::get("key")."%' ";
            if (Input::get("brand_id") != "") $sql .= " AND brand_id = ".Input::get("brand_id");
            if (Input::get("plan_code") != "") $sql .= " AND plan_code like '%".Input::get("plan_code")."%' ";//订货单号
            if (Input::get("plan_products_id") != "") $sql .= " AND ppp.id = ".Input::get("plan_products_id"); //根据采购项id
            if (Input::get("status") != "") $sql .= " AND ppp.status = ".Input::get("status"); //根据状态搜索
            
            $count = DB::select($con_sql.$sql);
            $plan_products = DB::select($select.$sql." order by created_at DESC limit ".$page_size*($page-1).",".$page_size);
            if(!empty($plan_products)){
            foreach ($plan_products as $v){
                $v->product_info =  SupplyItem::with(['unit'])->select("id","name","code","unit_id","sale_unit_id","volume_size","old_code")->find($v->product_id);
                $v->tax_purchase_price = number_format($v->tax_purchase_price/100,2);
                $v->no_tax_purchase_price = number_format($v->no_tax_purchase_price/100,2);
            }}
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["count"=>$count[0]->count,"lists"=>$plan_products,"error_type" =>[5=>"采购更换"]]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/planProducts", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  订货单操作添加采购项
     * */
    public function insertPlanProducts(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_product_ids' => 'required',
                'plan_code' => 'required',
                'new_address' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $plan_code = Input::get('plan_code');
            $plan_order_info = PMSPlanOrder::find($plan_code);
            if($plan_order_info->status !=1) {
                $response = Lang::get("pms_error.pms_plan_order_status_error_40018");
                break;
            }
           
            $plan_product_ids = json_decode((Input::get('plan_product_ids')));
            $address_str = "";
            
            //如果地址选择默认
            if(Input::get('new_address') == 1) {
                $old_shop_ids = PMSPlanProducts::select("shop_id")->leftJoin("pms_order","pms_order.pms_code","=","pms_plan_products.pms_code")
                        ->where("plan_code",$plan_code)
                        ->groupBy("shop_id")
                        ->get();
                
                $old_shop_arr = [];//原来shop_id的集合
                foreach ($old_shop_ids as $v){
                    $old_shop_arr[] = $v->shop_id;
                }
                
                $plan_product_ids_arr = [];
                foreach ($plan_product_ids as $v) {
                    $plan_product_ids_arr[] = $v->id;
                }

                $pms_codes = PMSPlanProducts::select("pms_plan_products.pms_code")
                        ->leftJoin("pms_order","pms_order.pms_code","=","pms_plan_products.pms_code")
                        ->whereNotIn("pms_order.shop_id",$old_shop_arr)
                        ->whereIn("pms_plan_products.id",$plan_product_ids_arr)
                        ->groupBy("pms_plan_products.pms_code")
                        ->get();

                $new_pms_codes = "";
                if (!empty($pms_codes)){
                    foreach($pms_codes as $v) {
                        $new_pms_codes .= $v->pms_code.",";
                    }
                    $new_pms_codes = trim($new_pms_codes,",");
                    $address_str = $this->addrssFun($new_pms_codes);
                }
            }
            
            try{
                DB::beginTransaction();
                $all_num = 0;
                
                foreach ($plan_product_ids as $v ) {
                    $plan_produc_info = PMSPlanProducts::find($v->id);
                    
                    if(empty($plan_produc_info)) throw new Exception("pms_error.pms_plan_order_product_error_40012"); 
                    if($plan_produc_info->status !=1) throw new Exception("pms_error.pms_plan_order_products_error_40015");
                    $all_num += $plan_produc_info->all_num;
                    $plan_produc_info->plan_code = $plan_code;
                    $plan_produc_info->status = 2;
                    $plan_produc_info->tax_purchase_price = $v->tax_purchase_price * 100;
                    $plan_produc_info->no_tax_purchase_price = $v->no_tax_purchase_price * 100;
                    if(!$plan_produc_info->save()) {
                        DB::rollback();
                        throw new Exception("pms_error.pms_plan_order_product_error_40016");
                    }

                }
                
                $plan_order_info->address = $plan_order_info->address . $address_str;
                $plan_order_info->all_num += $all_num;
                $plan_order_info->updated_type = 2;
                $plan_order_info->updated_by =  $res['user']->id;
                if(!$plan_order_info->save()) {
                    DB::rollback();
                    throw new Exception("pms_error.pms_plan_order_error_40017");
                }
                 DB::commit();
            }  catch (Exception $e){
                $response = Lang::get($e->getMessage());
            }
            
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/insertPlanProducts", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
   
        /**
     * 异常处理接口
     */
    public function error_handle(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',//订货单id
                'type'=>'required', //处理方式
                'args'=>'required', //[{"id":1,"product_id":1,"number":10}] 收货明细id和处理数量
                'is_create'=>'required',//是否新创建 采购单 0不 1创建
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            //传入参数
            $token = Input::get('token');
            $plan_code = Input::get('plan_code');
            $type = Input::get('type');
            $args = Input::get('args');
            $desc=Input::get("desc");
            $is_create=Input::get("is_create");

            $response = DB::transaction(function() use ($res,$plan_code,$type,$desc,$args,$is_create){
                $ppo=PMSPlanOrder::where("plan_code",$plan_code)->lockForUpdate()->first();//查找订货单 
                if(is_null($ppo)) {
                    return Lang::get("pms_error.pms_plan_order_error_40022");
                }
                if ($ppo->status!=2) {//不是待收货
                    return Lang::get("pms_error.pms_plan_order_status_error_40018");
                } 
                
                $ids=$args?json_decode($args,1):array(); 
                $shop_products = [];//根据门店进行分组
                $total_amount=0;
                foreach ($ids as $_id) {
                    //查找订货单商品
                    $ppp=PMSPlanProducts::find($_id["id"]);
                    if($ppp->last_num<$_id["number"]) { //如果大于剩余可清点数量 则报错
                        DB::rollback();
                        return Lang::get("pms_error.pms_plan_order_error_40028");
                    }
                    
                    //查找收货单商品
                    $prp=PMSReceiveProducts::where("plan_products_id",$ppp->id)->first();

                    //如果大于剩余可清点数量 则报错
                    if($prp->last_num<$_id["number"]) {
                        DB::rollback();
                        return Lang::get("pms_error.purchase_receive_order_product_notexit_65010");
                    }
                    //问题总数量 
                    $total_amount=$total_amount+$_id["number"];
                    //修改收货单商品
                    $prp->last_num=$prp->last_num-$_id["number"];//剩余清点数量 的与剩余数量减去清点数量
                    $prp->ready_num=$prp->ready_num+$_id["number"];
                    $prp->status=$prp->last_num==0?3:$prp->status;//如果已经清点完毕则 生成
                    $prp->save();
                    //修改收货单
                    $pro=PMSReceiveOrder::find($prp->receive_code);
                    if(is_null($pro)) { DB::rollback();return Lang::get("pms_error.purchase_receive_order_notexit_40025");}
                    if ($pro->status!=2) { DB::rollback();return Lang::get("pms_error.purchase_receive_order_status_40026");}//不是待收货或者已收货
                    $pro->error_num=$pro->error_num+$_id["number"];
                    $pro->status=($pro->error_num+$pro->ready_num)==$pro->all_num?3:$pro->status;//如果已经清点完毕则 修改状态完毕
                    $pro->save(); 
                    //添加收货明细
                    $prpr=new PMSReceiveProductsResult();
                    $prpr->pms_receive_products_id=$prp->id;
                    $prpr->receive_code=$prp->receive_code;
                    $prpr->pms_code=$prp->pms_code;
                    $prpr->plan_code=$prp->plan_code;
                    $prpr->shop_id=$pro->shop_id;
                    $prpr->source=2;
                    $prpr->type=$type;
                    $prpr->num=$_id["number"];
                    $prpr->product_id=$prp->product_id;
                    $prpr->comment=$desc;
                    $prpr->created_type=2;
                    $prpr->created_by=$res['user']->id;  
                    $prpr->save();      
                    //根据门店分组
                    $_id["prpr_id"]  = $prpr->id;
                    $shop_products[$pro->shop_id][] = $_id;
                    //修改订货单商品
                    $ppp->last_num=$ppp->last_num-$_id["number"];//剩余清点数量 的与剩余数量减去清点数量
                    $ppp->ready_num=$ppp->ready_num+$_id["number"];
                    $ppp->save(); 
                    //修改采购单商品
                    $pop=PMSOrderProducts::find($ppp->order_products_id);//查找采购单的采购需求
                    $pop->error_num=$pop->error_num+$_id["number"];//未满足数量也就是 异常处理数量加上清点数量
                    $pop->save(); 
                    //修改采购单
                    $pmo=PMSOrder::find($pop->pms_code);//查找采购单
                    $pmo->error_num=$pmo->error_num+$_id["number"];//未满足数量也就是 异常处理数量加上清点数量
                    if(($pmo->right_num+$pmo->error_num)==$pmo->all_num){//如果已签收 +异常的于需求量也就是 已经处理完毕 订单状态完成
                        $pmo->status=6;//如果已经清点完毕则 采购单状态
                        $pms_order_flow = new PMSOrderFlow();
                        $pms_order_flow->pms_code = $pmo->pms_code;
                        $pms_order_flow->status =6;
                        $pms_order_flow->operation =8;
                        $pms_order_flow->created_by =$res['user']->id;
                        $pms_order_flow->created_type =2;
                        $pms_order_flow->save();
                    }                    
                    $pmo->save();    
                }
                //修改订货单
                $ppo->error_num=$ppo->error_num+$total_amount;//订货单的异常数据处理
                $ppo->status=($ppo->error_num+$ppo->ready_num)==$ppo->all_num?3:$ppo->status;//如果已经清点完毕则 修改状态完毕
                $ppo->save();

                if($is_create==1){  
                    foreach ($shop_products as $shop_id=>$shop) {
                        //生成新的采购单
                        $pms_code =Common::createOrderId(); //'采购单号',
                        $pms_order = new PMSOrder();
                        $pms_order ->pms_code = $pms_code;
                        $pms_order ->source = 2;
                        $pms_order ->created_by = $res['user']->id;
                        $pms_order ->created_type = 2;
                        $pms_order ->shop_id = $shop_id;
                        $pms_order ->status = 1;
                        $pms_order ->type =$ppo->type;//类型和订货单采购类型一样
                        $pms_order->save();
                        //采购单操作记录
                        $pms_order_flow = new PMSOrderFlow();
                        $pms_order_flow->pms_code = $pms_code;
                        $pms_order_flow->status =1;
                        $pms_order_flow->operation =1;
                        $pms_order_flow->created_by =$res['user']->id;
                        $pms_order_flow->created_type = 2;
                        $pms_order_flow->save();
                        //采购单商品
                        $total_amount=0;
                        foreach($shop as $_id) {
                            $pmsop=new PMSOrderProducts();
                            $pmsop->pms_code=$pms_code;
                            $pmsop->product_id=$_id["product_id"];
                            $pmsop->all_num=$_id["number"];
                            $pmsop->error_num=0;
                            $pmsop->status=1;
                            $pmsop->created_by = $res['user']->id;
                            $pmsop->created_type = 2;                
                            $pmsop->save();
                            $total_amount+=$_id["number"];
                            
                            $prpr=PMSReceiveProductsResult::find($_id['prpr_id']);
                            $prpr->comment = empty($desc) ? "新生成采购单号：" . $pms_code : $desc.",新生成采购单号：" . $pms_code;//如果备注不为空后面加上，
                            $prpr->new_code = $pms_code;
                            $prpr->save();  
                        }
                        PMSOrder::where("pms_code",$pms_code)->update(array("all_num"=>$total_amount));
                    }
                }                
                return array('code' => 0, 'msg' => 'ok', 'result' => []);
            });  
                
        } while (false);
        Log::info("info", array("system" => "pms" ,"model" => "plan/error_handle", "event" => "error_handle", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  清点明细
     * */
    public function resultProducts(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $plan_code = Input::get("plan_code");
            $item_info = [];
            $result_products = PMSReceiveProductsResult::with(['StorageItem_info'])->where("plan_code",$plan_code)->orderBy("created_at","DESC")->get();
            
            if (!empty($result_products)) {
                foreach($result_products as $v){
                    $v -> created_by = PMSUser::created_by_user($v->created_type,$v -> created_by);
                    $v->product_info =  SupplyItem::with(['unit'])->select("id","name","code","unit_id","sale_unit_id","volume_size","old_code")->find($v->product_id);
                    $v->data_product_info = SupplyItem::with(['unit'])->select("id","name","code","unit_id","sale_unit_id","volume_size","old_code")->find($v->data_product_id);
                    $receive_products_info = PMSReceiveProducts::find($v->pms_receive_products_id);
                    $v -> tax_purchase_price = number_format($receive_products_info -> tax_purchase_price/100,2);
                    
                    $new_code_key =  $v->created_at . $v->new_code; //同一时间，同一个单号为一条数据。如果没有生成新单号，按时间来判断是不是同时生成的
                    if (isset($item_info[$new_code_key])) {
                        $item_info[$new_code_key]["list"][] = $v;
                    }else{
                        $item_info[$new_code_key]['new_code'] = $v->new_code;
                        $item_info[$new_code_key]['type'] = $v->type;
                        $item_info[$new_code_key]["list"] = [$v];
                    }
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["result_products"=>array_values($item_info),'type'=>PMSReceiveProductsResult::$type]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/resultProducts", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     *  商品汇总
     * */
    public function togetherProducts(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'plan_code' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $plan_code = Input::get("plan_code");
            $sql = "select sum(`all_num`) as all_num, count(id) as con,product_id,plan_code
                    from pms_plan_products  
                    where plan_code = '".$plan_code."' and is_split=0 ".
                    " group by product_id order by created_at desc";
            
            $plan_products = DB::select($sql);
            
            if (!empty($plan_products)) {
                foreach($plan_products as $v){
                    $error = DB::select("select sum(num) as num from pms_receive_products_result where plan_code='".$plan_code."' and product_id=".$v->product_id." and type<6");
                    $ready = DB::select("select sum(num) as num from pms_receive_products_result where plan_code='".$plan_code."' and product_id=".$v->product_id." and type=6");
                    $v->error_num = $error[0]->num ?: 0;
                    $v->ready_num = $ready[0]->num ?: 0;
                    $v->product_info =  SupplyItem::with(['unit','saleUnit'])->select("id","name","code","unit_id","sale_unit_id","volume_size","old_code")->find($v->product_id);
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["plan_products"=>$plan_products]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "plan/togetherProducts", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}